home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python-1.4 / Lib / pdb.py < prev    next >
Text File  |  1998-06-24  |  13KB  |  512 lines

  1. #! /usr/local/bin/python
  2.  
  3. # pdb.py -- finally, a Python debugger!
  4.  
  5. # (See pdb.doc for documentation.)
  6.  
  7. import string
  8. import sys
  9. import linecache
  10. import cmd
  11. import bdb
  12. import repr
  13.  
  14.  
  15. # Interaction prompt line will separate file and call info from code
  16. # text using value of line_prefix string.  A newline and arrow may
  17. # be to your liking.  You can set it once pdb is imported using the
  18. # command "pdb.line_prefix = '\n% '".
  19. # line_prefix = ': '    # Use this to get the old situation back
  20. line_prefix = '\n-> '    # Probably a better default
  21.  
  22. class Pdb(bdb.Bdb, cmd.Cmd):
  23.     
  24.     def __init__(self):
  25.         bdb.Bdb.__init__(self)
  26.         cmd.Cmd.__init__(self)
  27.         self.prompt = '(Pdb) '
  28.     
  29.     def reset(self):
  30.         bdb.Bdb.reset(self)
  31.         self.forget()
  32.     
  33.     def forget(self):
  34.         self.lineno = None
  35.         self.stack = []
  36.         self.curindex = 0
  37.         self.curframe = None
  38.     
  39.     def setup(self, f, t):
  40.         self.forget()
  41.         self.stack, self.curindex = self.get_stack(f, t)
  42.         self.curframe = self.stack[self.curindex][0]
  43.     
  44.     # Override Bdb methods (except user_call, for now)
  45.     
  46.     def user_line(self, frame):
  47.         # This function is called when we stop or break at this line
  48.         self.interaction(frame, None)
  49.     
  50.     def user_return(self, frame, return_value):
  51.         # This function is called when a return trap is set here
  52.         frame.f_locals['__return__'] = return_value
  53.         print '--Return--'
  54.         self.interaction(frame, None)
  55.     
  56.     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  57.         # This function is called if an exception occurs,
  58.         # but only if we are to stop at or just below this level
  59.         frame.f_locals['__exception__'] = exc_type, exc_value
  60.         if type(exc_type) == type(''):
  61.             exc_type_name = exc_type
  62.         else: exc_type_name = exc_type.__name__
  63.         print exc_type_name + ':', repr.repr(exc_value)
  64.         self.interaction(frame, exc_traceback)
  65.     
  66.     # General interaction function
  67.     
  68.     def interaction(self, frame, traceback):
  69.         self.setup(frame, traceback)
  70.         self.print_stack_entry(self.stack[self.curindex])
  71.         self.cmdloop()
  72.         self.forget()
  73.  
  74.     def default(self, line):
  75.         if line[:1] == '!': line = line[1:]
  76.         locals = self.curframe.f_locals
  77.         globals = self.curframe.f_globals
  78.         globals['__privileged__'] = 1
  79.         try:
  80.             code = compile(line + '\n', '<stdin>', 'single')
  81.             exec code in globals, locals
  82.         except:
  83.             if type(sys.exc_type) == type(''):
  84.                 exc_type_name = sys.exc_type
  85.             else: exc_type_name = sys.exc_type.__name__
  86.             print '***', exc_type_name + ':', sys.exc_value
  87.  
  88.     # Command definitions, called by cmdloop()
  89.     # The argument is the remaining string on the command line
  90.     # Return true to exit from the command loop 
  91.     
  92.     do_h = cmd.Cmd.do_help
  93.  
  94.     def do_break(self, arg):
  95.         if not arg:
  96.             print self.get_all_breaks() # XXX
  97.             return
  98.         # Try line number as argument
  99.         try:    
  100.             lineno = int(eval(arg))
  101.             filename = self.curframe.f_code.co_filename
  102.         except:
  103.             # Try function name as the argument
  104.             import codehack
  105.             try:
  106.                 func = eval(arg, self.curframe.f_globals,
  107.                         self.curframe.f_locals)
  108.                 if hasattr(func, 'im_func'):
  109.                     func = func.im_func
  110.                 code = func.func_code
  111.             except:
  112.                 print '*** Could not eval argument:', arg
  113.                 return
  114.             lineno = codehack.getlineno(code)
  115.             filename = code.co_filename
  116.  
  117.         # now set the break point
  118.         err = self.set_break(filename, lineno)
  119.         if err: print '***', err
  120.     do_b = do_break
  121.     
  122.     def do_clear(self, arg):
  123.         if not arg:
  124.             try:
  125.                 reply = raw_input('Clear all breaks? ')
  126.             except EOFError:
  127.                 reply = 'no'
  128.             reply = string.lower(string.strip(reply))
  129.             if reply in ('y', 'yes'):
  130.                 self.clear_all_breaks()
  131.             return
  132.         try:
  133.             lineno = int(eval(arg))
  134.         except:
  135.             print '*** Error in argument:', `arg`
  136.             return
  137.         filename = self.curframe.f_code.co_filename
  138.         err = self.clear_break(filename, lineno)
  139.         if err: print '***', err
  140.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  141.     
  142.     def do_where(self, arg):
  143.         self.print_stack_trace()
  144.     do_w = do_where
  145.     
  146.     def do_up(self, arg):
  147.         if self.curindex == 0:
  148.             print '*** Oldest frame'
  149.         else:
  150.             self.curindex = self.curindex - 1
  151.             self.curframe = self.stack[self.curindex][0]
  152.             self.print_stack_entry(self.stack[self.curindex])
  153.             self.lineno = None
  154.     do_u = do_up
  155.     
  156.     def do_down(self, arg):
  157.         if self.curindex + 1 == len(self.stack):
  158.             print '*** Newest frame'
  159.         else:
  160.             self.curindex = self.curindex + 1
  161.             self.curframe = self.stack[self.curindex][0]
  162.             self.print_stack_entry(self.stack[self.curindex])
  163.             self.lineno = None
  164.     do_d = do_down
  165.     
  166.     def do_step(self, arg):
  167.         self.set_step()
  168.         return 1
  169.     do_s = do_step
  170.     
  171.     def do_next(self, arg):
  172.         self.set_next(self.curframe)
  173.         return 1
  174.     do_n = do_next
  175.     
  176.     def do_return(self, arg):
  177.         self.set_return(self.curframe)
  178.         return 1
  179.     do_r = do_return
  180.     
  181.     def do_continue(self, arg):
  182.         self.set_continue()
  183.         return 1
  184.     do_c = do_cont = do_continue
  185.     
  186.     def do_quit(self, arg):
  187.         self.set_quit()
  188.         return 1
  189.     do_q = do_quit
  190.     
  191.     def do_args(self, arg):
  192.         if self.curframe.f_locals.has_key('__args__'):
  193.             print `self.curframe.f_locals['__args__']`
  194.         else:
  195.             print '*** No arguments?!'
  196.     do_a = do_args
  197.     
  198.     def do_retval(self, arg):
  199.         if self.curframe.f_locals.has_key('__return__'):
  200.             print self.curframe.f_locals['__return__']
  201.         else:
  202.             print '*** Not yet returned!'
  203.     do_rv = do_retval
  204.     
  205.     def do_p(self, arg):
  206.         self.curframe.f_globals['__privileged__'] = 1
  207.         try:
  208.             value = eval(arg, self.curframe.f_globals, \
  209.                     self.curframe.f_locals)
  210.         except:
  211.             if type(sys.exc_type) == type(''):
  212.                 exc_type_name = sys.exc_type
  213.             else: exc_type_name = sys.exc_type.__name__
  214.             print '***', exc_type_name + ':', `sys.exc_value`
  215.             return
  216.  
  217.         print `value`
  218.  
  219.     def do_list(self, arg):
  220.         self.lastcmd = 'list'
  221.         last = None
  222.         if arg:
  223.             try:
  224.                 x = eval(arg, {}, {})
  225.                 if type(x) == type(()):
  226.                     first, last = x
  227.                     first = int(first)
  228.                     last = int(last)
  229.                     if last < first:
  230.                         # Assume it's a count
  231.                         last = first + last
  232.                 else:
  233.                     first = max(1, int(x) - 5)
  234.             except:
  235.                 print '*** Error in argument:', `arg`
  236.                 return
  237.         elif self.lineno is None:
  238.             first = max(1, self.curframe.f_lineno - 5)
  239.         else:
  240.             first = self.lineno + 1
  241.         if last == None:
  242.             last = first + 10
  243.         filename = self.curframe.f_code.co_filename
  244.         breaklist = self.get_file_breaks(filename)
  245.         try:
  246.             for lineno in range(first, last+1):
  247.                 line = linecache.getline(filename, lineno)
  248.                 if not line:
  249.                     print '[EOF]'
  250.                     break
  251.                 else:
  252.                     s = string.rjust(`lineno`, 3)
  253.                     if len(s) < 4: s = s + ' '
  254.                     if lineno in breaklist: s = s + 'B'
  255.                     else: s = s + ' '
  256.                     if lineno == self.curframe.f_lineno:
  257.                         s = s + '->'
  258.                     print s + '\t' + line,
  259.                     self.lineno = lineno
  260.         except KeyboardInterrupt:
  261.             pass
  262.     do_l = do_list
  263.  
  264.     def do_whatis(self, arg):
  265.         try:
  266.             value = eval(arg, self.curframe.f_globals, \
  267.                     self.curframe.f_locals)
  268.         except:
  269.             if type(sys.exc_type) == type(''):
  270.                 exc_type_name = sys.exc_type
  271.             else: exc_type_name = sys.exc_type.__name__
  272.             print '***', exc_type_name + ':', `sys.exc_value`
  273.             return
  274.         code = None
  275.         # Is it a function?
  276.         try: code = value.func_code
  277.         except: pass
  278.         if code:
  279.             print 'Function', code.co_name
  280.             return
  281.         # Is it an instance method?
  282.         try: code = value.im_func.func_code
  283.         except: pass
  284.         if code:
  285.             print 'Method', code.co_name
  286.             return
  287.         # None of the above...
  288.         print type(value)
  289.     
  290.     # Print a traceback starting at the top stack frame.
  291.     # The most recently entered frame is printed last;
  292.     # this is different from dbx and gdb, but consistent with
  293.     # the Python interpreter's stack trace.
  294.     # It is also consistent with the up/down commands (which are
  295.     # compatible with dbx and gdb: up moves towards 'main()'
  296.     # and down moves towards the most recent stack frame).
  297.     
  298.     def print_stack_trace(self):
  299.         try:
  300.             for frame_lineno in self.stack:
  301.                 self.print_stack_entry(frame_lineno)
  302.         except KeyboardInterrupt:
  303.             pass
  304.     
  305.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  306.         frame, lineno = frame_lineno
  307.         if frame is self.curframe:
  308.             print '>',
  309.         else:
  310.             print ' ',
  311.         print self.format_stack_entry(frame_lineno, prompt_prefix)
  312.  
  313.  
  314.     # Help methods (derived from pdb.doc)
  315.  
  316.     def help_help(self):
  317.         self.help_h()
  318.  
  319.     def help_h(self):
  320.         print """h(elp)
  321.     Without argument, print the list of available commands.
  322.     With a command name as argument, print help about that command
  323.     "help pdb" pipes the full documentation file to the $PAGER
  324.     "help exec" gives help on the ! command"""
  325.  
  326.     def help_where(self):
  327.         self.help_w()
  328.  
  329.     def help_w(self):
  330.         print """w(here)
  331.     Print a stack trace, with the most recent frame at the bottom.
  332.     An arrow indicates the "current frame", which determines the
  333.     context of most commands."""
  334.  
  335.     def help_down(self):
  336.         self.help_d()
  337.  
  338.     def help_d(self):
  339.         print """d(own)
  340.     Move the current frame one level down in the stack trace
  341.     (to an older frame)."""
  342.  
  343.     def help_up(self):
  344.         self.help_u()
  345.  
  346.     def help_u(self):
  347.         print """u(p)
  348.     Move the current frame one level up in the stack trace
  349.     (to a newer frame)."""
  350.  
  351.     def help_break(self):
  352.         self.help_b()
  353.  
  354.     def help_b(self):
  355.         print """b(reak) [lineno | function]
  356.     With a line number argument, set a break there in the current
  357.     file.  With a function name, set a break at the entry of that
  358.     function.  Without argument, list all breaks."""
  359.  
  360.     def help_clear(self):
  361.         self.help_cl()
  362.  
  363.     def help_cl(self):
  364.         print """cl(ear) [lineno]
  365.     With a line number argument, clear that break in the current file.
  366.     Without argument, clear all breaks (but first ask confirmation)."""
  367.  
  368.     def help_step(self):
  369.         self.help_s()
  370.  
  371.     def help_s(self):
  372.         print """s(tep)
  373.     Execute the current line, stop at the first possible occasion
  374.     (either in a function that is called or in the current function)."""
  375.  
  376.     def help_next(self):
  377.         self.help_n()
  378.  
  379.     def help_n(self):
  380.         print """n(ext)
  381.     Continue execution until the next line in the current function
  382.     is reached or it returns."""
  383.  
  384.     def help_return(self):
  385.         self.help_r()
  386.  
  387.     def help_r(self):
  388.         print """r(eturn)
  389.     Continue execution until the current function returns."""
  390.  
  391.     def help_continue(self):
  392.         self.help_c()
  393.  
  394.     def help_cont(self):
  395.         self.help_c()
  396.  
  397.     def help_c(self):
  398.         print """c(ont(inue))
  399.     Continue execution, only stop when a breakpoint is encountered."""
  400.  
  401.     def help_list(self):
  402.         self.help_l()
  403.  
  404.     def help_l(self):
  405.         print """l(ist) [first [,last]]
  406.     List source code for the current file.
  407.     Without arguments, list 11 lines around the current line
  408.     or continue the previous listing.
  409.     With one argument, list 11 lines starting at that line.
  410.     With two arguments, list the given range;
  411.     if the second argument is less than the first, it is a count."""
  412.  
  413.     def help_args(self):
  414.         self.help_a()
  415.  
  416.     def help_a(self):
  417.         print """a(rgs)
  418.     Print the argument list of the current function."""
  419.  
  420.     def help_p(self):
  421.         print """p expression
  422.     Print the value of the expression."""
  423.  
  424.     def help_exec(self):
  425.         print """(!) statement
  426.     Execute the (one-line) statement in the context of
  427.     the current stack frame.
  428.     The exclamation point can be omitted unless the first word
  429.     of the statement resembles a debugger command.
  430.     To assign to a global variable you must always prefix the
  431.     command with a 'global' command, e.g.:
  432.     (Pdb) global list_options; list_options = ['-l']
  433.     (Pdb)"""
  434.  
  435.     def help_quit(self):
  436.         self.help_q()
  437.  
  438.     def help_q(self):
  439.         print """q(uit)    Quit from the debugger.
  440.     The program being executed is aborted."""
  441.  
  442.     def help_pdb(self):
  443.         help()
  444.  
  445. # Simplified interface
  446.  
  447. def run(statement, globals=None, locals=None):
  448.     Pdb().run(statement, globals, locals)
  449.  
  450. def runeval(expression, globals=None, locals=None):
  451.     return Pdb().runeval(expression, globals, locals)
  452.  
  453. def runctx(statement, globals, locals):
  454.     # B/W compatibility
  455.     run(statement, globals, locals)
  456.  
  457. def runcall(*args):
  458.     return apply(Pdb().runcall, args)
  459.  
  460. def set_trace():
  461.     Pdb().set_trace()
  462.  
  463. # Post-Mortem interface
  464.  
  465. def post_mortem(t):
  466.     p = Pdb()
  467.     p.reset()
  468.     while t.tb_next <> None: t = t.tb_next
  469.     p.interaction(t.tb_frame, t)
  470.  
  471. def pm():
  472.     import sys
  473.     post_mortem(sys.last_traceback)
  474.  
  475.  
  476. # Main program for testing
  477.  
  478. TESTCMD = 'import x; x.main()'
  479.  
  480. def test():
  481.     run(TESTCMD)
  482.  
  483. # print help
  484. def help():
  485.     import os
  486.     for dirname in sys.path:
  487.         fullname = os.path.join(dirname, 'pdb.doc')
  488.         if os.path.exists(fullname):
  489.             sts = os.system('${PAGER-more} '+fullname)
  490.             if sts: print '*** Pager exit status:', sts
  491.             break
  492.     else:
  493.         print 'Sorry, can\'t find the help file "pdb.doc"',
  494.         print 'along the Python search path'
  495.  
  496. # When invoked as main program, invoke the debugger on a script
  497. if __name__=='__main__':
  498.     import sys
  499.     import os
  500.     if not sys.argv[1:]:
  501.         print "usage: pdb.py scriptfile [arg] ..."
  502.         sys.exit(2)
  503.  
  504.     filename = sys.argv[1]    # Get script filename
  505.  
  506.     del sys.argv[0]        # Hide "pdb.py" from argument list
  507.  
  508.     # Insert script directory in front of module search path
  509.     sys.path.insert(0, os.path.dirname(filename))
  510.  
  511.     run('execfile(' + `filename` + ')', {'__name__': '__main__'})
  512.